package org.example.demo3.untils;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * Token工具类，用于从请求头中提取Token并获取用户ID
 */
@Component
@RequiredArgsConstructor
public class TokenUtil {

    private final JwtUtil jwtUtil;

    /**
     * 从Authorization请求头中提取Token
     * @param authorizationHeader 请求头中的Authorization字段值
     * @return 提取出的Token
     */
    public String extractToken(String authorizationHeader) {
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            return authorizationHeader.substring(7);
        }
        throw new RuntimeException("无效的Authorization头");
    }

    /**
     * 从Token中获取用户ID
     * @param token JWT Token
     * @return 用户ID
     */
    public Long getUserIdFromToken(String token) {
        Long userId = jwtUtil.validateAccessToken(token);
        if (userId == null) {
            throw new RuntimeException("无效的Token或Token已过期");
        }
        return userId;
    }

    /**
     * 从Authorization请求头中获取用户ID
     * @param authorizationHeader 请求头中的Authorization字段值
     * @return 用户ID
     */
    public Long getUserIdFromHeader(String authorizationHeader) {
        String token = extractToken(authorizationHeader);
        return getUserIdFromToken(token);
    }
} 